//
//  ViewController.swift
//  Emoticon
//
//  Created by 李锡鹏 on 2017/6/10.
//  Copyright © 2017年 李锡鹏. All rights reserved.
//

import UIKit


class ViewController: UIViewController {
    
    @IBAction func clickComPose(_ sender: Any) {
        let attrString = textView.attributedText
        var strM = String()
        attrString?.enumerateAttributes(in: NSRange(location:0,length:(attrString?.length)!), options: [], using: { (dict, range, _) in
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment {
                print("图片:\(attachment.emoticon.chs)")
                strM = strM + attachment.emoticon.chs!
            }
            else {
                let str = (attrString?.string as! NSString).substring(with: range)
                print("文字:\(str)")
                strM = strM + str
            }
        })
        print(strM)
    }
    @IBOutlet weak var textView: UITextView!
    private lazy var emoticonView : EmoticonView = EmoticonView { [weak self] (emoticon) in
        self?.insertEmoticon(em:emoticon)
        self?.insertImageEmoticon(em:emoticon)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        textView.inputView = emoticonView
        textView.becomeFirstResponder()
        
        
    }
    func insertImageEmoticon(em:Emoticon) {
        print("插入图片")
        if em.imagePath == "" {
            return
        }
        let attachment = EmoticonAttachment(emoticon: em)
        attachment.image = UIImage(contentsOfFile: em.imagePath!)
        let lineheigth = textView.font?.lineHeight
        attachment.bounds = CGRect(x: 0, y: -4, width: lineheigth!, height: lineheigth!)
        let imageText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
        imageText.addAttribute(NSFontAttributeName, value: textView.font as Any, range: NSRange(location: 0, length: 1))
        let strM = NSMutableAttributedString(attributedString: textView.attributedText)
        strM.replaceCharacters(in: textView.selectedRange, with: imageText)
        let  range = textView.selectedRange
        textView.attributedText = strM
        textView.selectedRange = NSRange(location: range.location+1, length: 0)
    }
    func insertEmoticon(em:Emoticon) {
        if em.isEmpty {
            return
        }
        if em.isRemoved {
            textView.deleteBackward()
            return
        }
        if let emoji = em.emoji {
            textView.replace(textView.selectedTextRange!, withText: emoji)
            return
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    
}

